import { defineComponent, onMounted, PropType, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus/lib/index';
import * as RouteNames from '@/router/consts';
import API from '@/services';
import { useRouter } from 'vue-router';
import Table from '@/components/Table/index';
import './indexlibTable.scss';
//指标库表格业务组件
const IndexlibTable = defineComponent({
  name: 'IndexlibTable',
  props: {
    content: {
      type: String as PropType<string>,
      default: ''
    },
    filterTagId: {
      type: String as PropType<string>,
      default: -1
    },
    subType: {
      type: String as PropType<string>,
      default: '-1'
    },
    searchType: {
      type: String as PropType<string>,
      default: 'derived' // atom ,derived
    }
  },
  setup: (props, { slots, attrs, emit }) => {
    const router = useRouter();

    const state = reactive({
      loading: false,
      pageNum: 1,
      tableData: [] as any[],
      pageSize: 10,
      total: 0,
      order: undefined as any,
      sortBy: undefined as any,
      atomTableColumn: [
        {
          prop: 'cnName',
          label: '指标名称',
          width: 210,
          default: ({ row }: any) => (
            <a
              class="derivedCnName-link"
              href="javascript:void(0)"
              onClick={() => {
                goDetail(row.id);
              }}
            >
              {row.cnName}
            </a>
          )
        },
        {
          prop: 'subTypeDesc',
          label: '指标分类'
        },
        {
          prop: 'businessMeaning',
          label: '业务含义'
        },
        {
          prop: 'businessOwner',
          label: '业务负责人',
          width: '215'
        },
        {
          prop: 'techOwner',
          label: '研发负责人',
          width: '215'
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: '165'
        },
        {
          prop: 'pageViewCount',
          label: '热度',
          width: '120',
          sortable: true,
          default: ({ row }: any) => (
            <div class="hot-degree">{row.pageViewCount}</div>
          )
        },
        {
          prop: 'option',
          label: '操作',
          width: '110',
          default: ({ row, $index }: any) => (
            <el-button
              type="text"
              onClick={(e: any) => {
                e.preventDefault();
                toggleFavoriteStatus(row, $index, state.tableData);
              }}
            >
              {row.favoriteStatus ? '取消收藏' : '收藏'}
            </el-button>
          )
        }
      ], //原子
      derivedTableColumn: [
        {
          prop: 'derivedCnName',
          label: '指标名称',
          width: 210,
          default: ({ row }: any) => (
            <a
              class="derivedCnName-link"
              href="javascript:void(0)"
              onClick={() => {
                goDetail(row.id);
              }}
            >
              {row.derivedCnName}
            </a>
          )
        },
        {
          prop: 'subTypeDesc',
          label: '指标分类'
        },
        {
          prop: 'businessMeaning',
          label: '业务含义'
        },
        {
          prop: 'dimensionName',
          label: '支持维度'
        },
        {
          prop: 'businessOwner',
          label: '业务负责人',
          width: '215'
        },
        {
          prop: 'techOwner',
          label: '研发负责人',
          width: '215'
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: '165'
        },
        {
          prop: 'pageViewCount',
          label: '热度',
          width: '120',
          sortable: true,
          default: ({ row }: any) => (
            <div class="hot-degree">{row.pageViewCount}</div>
          )
        },
        {
          prop: 'option',
          label: '操作',
          width: '110',
          default: ({ row, index }: any) => (
            <el-button
              type="text"
              onClick={(e: any) => {
                e.preventDefault();
                toggleFavoriteStatus(row, index, state.tableData);
              }}
            >
              {row.favoriteStatus ? '取消收藏' : '收藏'}
            </el-button>
          )
        }
      ]
    });

    //查询表格数据
    const getListData = async () => {
      state.loading = true;
      const params: any = {
        pageSize: state.pageSize,
        pageNum: state.pageNum
      };

      if (props.filterTagId !== '-1') {
        params['subjectId'] = props.filterTagId;
      }
      if (props.subType !== '-1') {
        params['subType'] = props.subType;
      }
      let data, code;
      if (props.searchType === 'derived') {
        if (props.content) {
          params['content'] = props.content;
        }
        ({ data, code } = await API.derivedMetricsLibrary.getList({
          ...params,
          order: state.order,
          sortBy: state.sortBy
        }));
      } else if (props.searchType === 'atom') {
        if (props.content) {
          params['keyword'] = props.content;
        }
        ({ data, code } = await API.atomicMetricsLibrary.postList({
          ...params,
          order: state.order,
          sortBy: state.sortBy
        }));
      }

      if (code === 200) {
        state.tableData = (data as any).list;
        state.total = (data as any).total * 1;
      }
      state.loading = false;
    };
    //改变条数
    const handleSizeChange = (pageSize: number) => {
      state.pageSize = pageSize;
      getListData();
    };
    //翻页
    const handleCurrentChange = (pageNum: number) => {
      state.pageNum = pageNum;
      getListData();
    };
    //排序
    const sortTable = (column: any) => {
      if (column && column.order) {
        const { prop, order } = column;
        state.order = order === 'ascending' ? 1 : 2;
        state.sortBy = prop;
      } else {
        state.order = undefined;
        state.sortBy = undefined;
      }
      getListData();
    };
    // 去往详情页
    const goDetail = (id: number) => {
      if (props.searchType === 'derived') {
        router.push({
          name: RouteNames.ROUTE_INDEXDETAIL,
          query: { id }
        });
      } else if (props.searchType === 'atom') {
        router.push({
          name: RouteNames.ROUTE_ATOM_INDEXDETAIL,
          query: { id }
        });
      }
    };
    //收藏状态
    const toggleFavoriteStatus = async (
      row: any,
      index: any,
      tableData: any
    ) => {
      state.loading = true;
      if (row) {
        const { favoriteStatus, id } = row;

        if (favoriteStatus === 1) {
          // 取消
          const { code } = await API.favoriteMetrics.putFavoriteMetricsById({
            id
          });
          if (code === 200) {
            state.tableData[index].favoriteStatus = 0;
            ElMessage.success('取消收藏成功');
          } else {
            ElMessage.error('取消收藏失败');
          }
        } else {
          //添加
          const { code } = await API.favoriteMetrics.getFavoriteMetricsById({
            id
          });
          if (code === 200) {
            state.tableData[index].favoriteStatus = 1;
            ElMessage.success('收藏成功');
          } else {
            ElMessage.error('收藏失败');
          }
        }
        state.loading = false;
      }
    };

    watch(
      () => props.content,
      (value: any) => {
        if (!value) {
          getListData();
        }
      }
    );
    watch(
      () => props.filterTagId,
      (value: any) => {
        getListData();
      }
    );
    watch(
      () => props.subType,
      (value: any) => {
        getListData();
      }
    );

    onMounted(() => {
      getListData();
    });

    return () => {
      return (
        <Table
          v-loading={state.loading}
          data={state.tableData}
          column={
            props.searchType === 'derived'
              ? state.derivedTableColumn
              : state.atomTableColumn
          }
          onSortChange={sortTable}
          onPageCurrentChange={handleCurrentChange}
          onPageSizeChange={handleSizeChange}
          pagination={{
            total: state.total,
            currentPage: state.pageNum,
            pageSize: state.pageSize
          }}
        />
      );
    };
  }
});

export default IndexlibTable;
